<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryRef" size="large" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="发起人姓名" prop="promoterName">
        <el-input v-model="queryParams.promoterName" placeholder="请输入发起人姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="销售负责人" prop="promoterName">
        <el-input v-model="queryParams.saleName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="往来信息" name="first">
    <el-table v-loading="loading" border :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column label="往来客户名称" align="center" show-overflow-tooltip width="300" prop="customerName" />
      <el-table-column label="销售负责人" align="center" prop="saleName" />
      <el-table-column label="出库起始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出库截至日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售总金额" align="center" prop="total" />
      <el-table-column label="毛利" align="center" prop="profit" />
      <!-- <el-table-column label="毛利率%" align="center" prop="profitRatio" /> -->
      <el-table-column label="发起人" align="center" prop="promoterName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="个人绩效总金额" align="center" prop="personTotal" />
      <el-table-column label="个人已发放" align="center" prop="personAlready" />
      <el-table-column label="个人待发放" align="center" prop="personWait" />
      <el-table-column label="部门绩效总金额" align="center" prop="deptTotal" />
      <el-table-column label="部门绩效已发放" align="center" prop="deptAlready" />
      <el-table-column label="部门绩效待发放" align="center" prop="deptWait" />
      <el-table-column label="操作" fixed="right" align="center" width="320" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" v-if="userStore.name == 'wuzg'" icon="Edit"
            @click="handleUpdateData(scope.row, 'edit')">修改</el-button>
          <el-button link type="primary" icon="search" @click="handleUpdate(scope.row)">查看出库单数据</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-tab-pane>
    <el-tab-pane label="绩效统计" name="second">
      <el-table v-loading="loading" border :data="mergeList" @selection-change="handleSelectionChange">
        <el-table-column label="销售负责人" align="center" prop="saleName" />
        <el-table-column label="个人绩效总金额" align="center" prop="personTotal" />
      <el-table-column label="个人已发放" align="center" prop="personAlready" />
      <el-table-column label="个人待发放" align="center" prop="personWait" />
      <el-table-column label="部门绩效总金额" align="center" prop="deptTotal" />
      <el-table-column label="部门绩效已发放" align="center" prop="deptAlready" />
      <el-table-column label="部门绩效待发放" align="center" prop="deptWait" />
    </el-table>
    </el-tab-pane>
  </el-tabs>

    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="customerRef" :model="form" size="large" :rules="rules" label-width="120px">
        <el-form-item label="往来客户" prop="customerId">
          <!-- <el-input v-model="form.customerId" placeholder="请输入往来客户id" /> -->
          <el-select v-model="form.customerId" filterable remote reserve-keyword placeholder="请输入关键字"
            :remote-method="selectCompany" :loading="loadingQuery" style="width: 600px" @change="setHousekeeperName">
            <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="销售负责人" prop="saleId">
          <el-select @change="setPersonName" filterable v-model="form.saleId" placeholder="请选择" clearable style="width: 200px">
            <el-option v-for="dict in userList" clearable :key="dict.userId" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出库起始日期" prop="startDate">
          <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择出库起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出库截至日期" prop="endDate">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择出库截至日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <customerView ref="customerViewRef"></customerView>
  </div>

</template>

<script setup name="Customer">
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, auditCustomer, listCustomerSale,merge } from "@/api/project/customer";
import { listCompany } from "@/api/project/project";
import customerView from "./customerView.vue"
import { ElLoading } from 'element-plus'

import useUserStore from '@/store/modules/user'
import { listAllUser, getUser, getPosts } from "@/api/system/user";
import { listLog, getLog, delLog, addLog, updateLog } from "@/api/project/log";


const userStore = useUserStore()

const { proxy } = getCurrentInstance();
const { audit_type } = proxy.useDict('audit_type');
const customerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const totalSale = ref(0);
const title = ref("");
const companyList = ref([]);
const loadingQuery = ref(false)
const drawer = ref(false)
const saleList = ref([]);
const customerViewRef = ref()
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    status: "2",
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null,
    refresh: "1",
    housekeeperProject: ''
  },
  queryParamsSale: {
    pageNum: 1,
    pageSize: 10,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    status: "2",
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null,
    refresh: "1",
    housekeeperProject: ''
  },
  rules: {
    customerId: [{ required: true, message: "请选择往来客户", trigger: "blur" }],
    startDate: [{ required: true, message: "请选择起始日期", trigger: "blur" }],
    endDate: [{ required: true, message: "请选择截止日期", trigger: "blur" }],
  }
});

const { queryParams, queryParamsSale, form, rules } = toRefs(data);
const currentType = ref()
/** 修改按钮操作 */
function handleUpdateData(row, type) {
  currentType.value = type
  if (type == 'edit') {
    reset();
    const _id = row.id || ids.value
    getCustomer(_id).then(response => {
      form.value = response.data;

      if (form.value.customerName) {
        selectCompany(form.value.customerName)
      }

      open.value = true;
      title.value = "修改往来客户";

    });
  } else {
    nextTick(() => {
      if (customerViewRef.value) {
        customerViewRef.value.handleUpdate(row)
      } else {
        console.error("allocationRef is not available yet!");
      }
    });
  }


}


function setPersonName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = userList.value.filter((obj) => obj.userId === id);
  // 清空 projectTypeName 字段
  form.value.saleName = '';
  console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

  form.value.saleName = filteredObjects[0]?.nickName
}



function selectCompany(query) {
  console.log("queryquery", query);
  loadingQuery.value = true
  let params = {
    companyName: query
  }
  listCompany(params).then((response) => {
    companyList.value = response.data
    loadingQuery.value = false
  });
}


const setHousekeeperName = (id) => {

  if (id == undefined) {
    form.value.customerName = '';
    return
  }
  const filteredObjects = companyList.value.find((obj) => obj.id === id);
  form.value.customerName = '';
  console.log("filteredObjects", filteredObjects);
  form.value.customerName = filteredObjects?.companyName || '';
  console.log("customerName", id, form.value.housekeeperName);
}

/** 查询往来客户列表 */
function getList() {
  loading.value = true;
  listCustomer(queryParams.value).then(response => {
    customerList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

function getListSale() {
  loading.value = true;
  getSaleListPage()
}


const mergeList = ref([])

function getMerge(){
  let params = {
    saleName:queryParams.value.saleName,
  }
  merge(params).then(response => {
    console.log("统计",response);
    mergeList.value = response
  });

}

const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName

  if (activeName.value == 'second') {
    getMerge()
  }


}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    status: null,
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null
  };
  proxy.resetForm("customerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加往来客户";
}
const userList = ref([])
onMounted(() => {
  listAllUser().then((response) => {
    userList.value = response
  });
  getMerge()
});

/** 修改按钮操作 */
function handleUpdate(row) {

  nextTick(() => {
    // open.value = true; 
    title.value = "详细信息";
    if (customerViewRef.value) {
      customerViewRef.value.handleUpdate(row)

    } else {
      console.error("allocationRef is not available yet!");
    }
  });

  // getCustomer(row.id).then(response => {
  //   form.value = response.data;
  //   if (form.value.customerName) {
  //     selectCompany(form.value.customerName)
  //   }
  //   open.value = true;
  //   title.value = "详细信息";

  //   getSaleListPage()

  // });
}


function getSaleInfo(row, type) {
  queryParams.value.refresh = type
  queryParams.value.id = row.id
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '数据查询中...' });
  listCustomerSale(queryParams.value).then(response => {
    console.log("统计结果:", response);
    if (response) {
      loadingInstance.close()
      proxy.$modal.msgSuccess("查询完成");
      form.value = response.data
    }
  });
}

function getSaleListPage() {
  queryParamsSale.value.housekeeperProject = form.value.customerId
  queryParamsSale.value.startDate = form.value.startDate
  queryParamsSale.value.endDate = form.value.endDate
  listCustomerSale(queryParamsSale.value).then(response => {
    console.log("出库单数据", response);
    saleList.value = response.data.rows;
    totalSale.value = response.data.total;
    loading.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["customerRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        auditCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("成功");
          open.value = false;
          getList();
        });
      } else {
        addCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除往来客户编号为"' + _ids + '"的数据项？').then(function () {
    return delCustomer(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
}

getList();
</script>
